package com.shujia.rec.service.impl;

import com.shujia.rec.dao.ContactDao;
import com.shujia.rec.domain.ContactEntity;
import com.shujia.rec.service.ContactService;
import com.shujia.rec.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

@Service("contactService")
public class ContactServiceImpl implements ContactService {

    @Autowired
    ContactDao contactDao;

    @Override
    public List<ContactEntity> selectByIds(List<String> ids) {
        return contactDao.selectByIds(ids);
    }

    @Override
    public List<ContactEntity> listAll(long size) {

        return contactDao.listAll(size);
    }

    @Override
    public List<ContactEntity> topN() {

        //从redis中获取topN商品列表
        Jedis jedis = RedisUtil.getJedis();
        List<String> lrange = jedis.lrange("rec:topn", 0, -1);

        ArrayList<String> ids = new ArrayList<>();
        for (String s : lrange) {
            String proId = s.split(",")[0];
            ids.add(proId);
        }

        jedis.close();

        if (ids.isEmpty()){
            return new ArrayList<>();
        }

        //返回热门商品
        return contactDao.selectByIds(ids);
    }

    @Override
    public ContactEntity selectById(String id) {
        return contactDao.selectById(Integer.valueOf(id));
    }
}
